package com.molichuxing.gateway.bff.order.services.impl;

import com.molichuxing.framework.dto.Paged;
import com.molichuxing.framework.exception.BizException;
import com.molichuxing.framework.utils.DateUtil;
import com.molichuxing.framework.utils.ObjectCastUtil;
import com.molichuxing.gateway.bff.order.convertor.Convert;
import com.molichuxing.gateway.bff.order.entity.request.create.EnterpriseLeaseConfirmCreateVo;
import com.molichuxing.gateway.bff.order.entity.request.create.EnterprisePayCreateVo;
import com.molichuxing.gateway.bff.order.entity.request.create.OrderEnterpriseCreateVo;
import com.molichuxing.gateway.bff.order.entity.response.*;
import com.molichuxing.gateway.bff.order.services.OrderEnterpriseBffService;
import com.molichuxing.services.business.dto.response.EnterpriseScheduleBizDto;
import com.molichuxing.services.business.dto.response.OrderEnterpriseBizDto;
import com.molichuxing.services.business.dto.response.OrderEnterpriseCarBizDto;
import com.molichuxing.services.business.dto.response.VehicleNameBizDto;
import com.molichuxing.services.business.service.EnterpriseScheduleBizService;
import com.molichuxing.services.business.service.OrderEnterpriseBizService;
import com.molichuxing.services.business.service.VehicleBizService;
import com.molichuxing.services.infrastructure.dto.request.create.ContractEnterpriseCreateDto;
import com.molichuxing.services.infrastructure.dto.request.create.PaymentEnterpriseCreateDto;
import com.molichuxing.services.infrastructure.dto.response.*;
import com.molichuxing.services.infrastructure.service.*;
import com.molichuxing.services.property.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 企业订单bff
 *
 * @Author zoumingyu
 * @Date 2020年06月03日
 */
@Service("orderEnterpriseBffService")
public class OrderEnterpriseBffServiceImpl implements OrderEnterpriseBffService {
    private static final Logger logger = LoggerFactory.getLogger(OrderEnterpriseBffServiceImpl.class);

    @Resource
    private OrderEnterpriseBizService orderEnterpriseBizService;

    @Resource
    private OrderEnterpriseService orderEnterpriseService;

    @Resource
    private EnterpriseCarService enterpriseCarService;

    @Resource
    private EnterpriseCarHandoverService enterpriseCarHandoverService;

    @Resource
    private EnterpriseScheduleService enterpriseScheduleService;

    @Resource
    private EnterpriseScheduleBizService enterpriseScheduleBizService;

    @Resource
    private PaymentEnterpriseService paymentEnterpriseService;


    @Resource
    private CarService carService;

    @Resource
    private VehicleBizService vehicleBizService;

    @Resource
    private VehicleColorService vehicleColorService;

    @Resource
    private ContractEnterpriseService contractEnterpriseService;

    @Resource
    private EnterpriseStateFlowService enterpriseStateFlowService;

    @Resource
    private EnterpriseService enterpriseService;

    @Resource
    private VehicleModleService vehicleModleService;


    /**
     * 获取企业订单基本信息
     *
     * @param orderCode 订单号
     * @return OrderEnterpriseBaseVo
     */
    @Override
    public OrderEnterpriseBaseVo getEnterpriseBase(Long orderCode) {
        // 查询订单信息
        OrderEnterpriseDto orderEnterpriseDto = orderEnterpriseService.getEnterprise(orderCode);
        if (orderEnterpriseDto == null) {
            return null;
        }
        // 查询订单合同信息
        ContractEnterpriseDto contractEnterpriseDto = contractEnterpriseService.getContractByOrderCode(
                orderCode, null, ContractEnterpriseTypeEnum.ORDER_CONTRACT);

        // 查询企业信息
        EnterpriseDto enterpriseDto = enterpriseService.getEnterprise(orderEnterpriseDto.getEnterpriseId());

        return Convert.toOrderEnterpriseBaseVo(orderEnterpriseDto, contractEnterpriseDto, enterpriseDto);
    }

    /**
     * 获取企业订单车辆明细
     *
     * @param orderCode 订单号
     * @return OrderEnterpriseCarDetailVo
     */
    @Override
    public OrderEnterpriseCarDetailVo getEnterpriseCar(Long orderCode) {
        // 获取订单车辆明细信息
        List<EnterpriseCarDto> enterpriseCars = enterpriseCarService.getEnterpriseCar(orderCode);
        if (enterpriseCars == null || enterpriseCars.isEmpty()) {
            return null;
        }
        Map<Integer, List<EnterpriseCarDto>> enterpriseCarMap = new HashMap<>();
        // 车辆ids
        List<Integer> carIds = new ArrayList<>(enterpriseCars.size());
        // 车型ids
        Set<Integer> modelIdSet = new HashSet<>();
        // 颜色ids
        Set<Integer> colorIdSet = new HashSet<>();
        for (EnterpriseCarDto dto : enterpriseCars) {
            colorIdSet.add(dto.getColorId());
            carIds.add(dto.getCarId());
            modelIdSet.add(dto.getModelId());
            if (enterpriseCarMap.get(dto.getModelId()) == null) {
                List<EnterpriseCarDto> list = new ArrayList<>();
                list.add(dto);
                enterpriseCarMap.put(dto.getModelId(), list);
            } else {
                enterpriseCarMap.get(dto.getModelId()).add(dto);
            }
        }
        // 查询车辆
        Map<Integer, CarDto> carMap = carService.getCarByIds(carIds);
        // 查询车型
        ArrayList<Integer> ids = new ArrayList<>(modelIdSet.size());
        ids.addAll(modelIdSet);
        Map<Integer, VehicleNameBizDto> vehicleMap = vehicleBizService.getCarByModelNameList(ids);
        // 查询颜色
        ids = new ArrayList<>(colorIdSet.size());
        ids.addAll(colorIdSet);
        Map<Integer, VehicleColorDto> colorMap = vehicleColorService.getVehicleColors(ids);

        return Convert.toOrderEnterpriseCarDetailVo(orderCode, enterpriseCarMap, carMap, vehicleMap, colorMap);
    }

    /**
     * 获取企业订单交车信息
     *
     * @param orderCode 订单号
     * @return List
     */
    @Override
    public List<OrderEnterpriseCarHandoverVo> getEnterpriseCarDelivery(Long orderCode) {
        // 获取企业订单车辆交车信息
        List<EnterpriseCarHandoverDto> enterpriseCarDeliverys = enterpriseCarHandoverService.getEnterpriseCarDelivery(orderCode);
        if (enterpriseCarDeliverys == null || enterpriseCarDeliverys.isEmpty()) {
            return null;
        }
        // 车辆ids
        List<Integer> carIds = new ArrayList<>(enterpriseCarDeliverys.size());
        // 车型ids
        Set<Integer> modelIdSet = new HashSet<>();
        // 颜色ids
        Set<Integer> colorIdSet = new HashSet<>();
        for (EnterpriseCarHandoverDto dto : enterpriseCarDeliverys) {
            colorIdSet.add(dto.getColorId());
            carIds.add(dto.getCarId());
            modelIdSet.add(dto.getModelId());
        }
        // 查询车辆
        Map<Integer, CarDto> carMap = carService.getCarByIds(carIds);
        // 查询车型
        ArrayList<Integer> ids = new ArrayList<>(modelIdSet.size());
        ids.addAll(modelIdSet);
        Map<Integer, VehicleNameBizDto> vehicleMap = vehicleBizService.getCarByModelNameList(ids);
        // 查询颜色
        ids = new ArrayList<>(colorIdSet.size());
        ids.addAll(colorIdSet);
        Map<Integer, VehicleColorDto> colorMap = vehicleColorService.getVehicleColors(ids);
        // 查询订单交车单信息
        List<ContractEnterpriseDto> deliverys = contractEnterpriseService.getContractListByOrderCode(orderCode, null, ContractEnterpriseTypeEnum.CAR_CONTRACT);
        Map<Integer, ContractEnterpriseDto> deliveryMap = null;
        if (deliverys != null && !deliverys.isEmpty()) {
            deliveryMap = new HashMap<>();
            for (ContractEnterpriseDto delivery : deliverys) {
                deliveryMap.put(delivery.getCarId(), delivery);
            }
        }

        return Convert.toOrderEnterpriseCarHandoverVo(enterpriseCarDeliverys, carMap, vehicleMap, colorMap, deliveryMap);
    }

    /**
     * 获取企业订单还款信息
     *
     * @param orderCode 订单号
     * @return OrderEnterpriseRepaymentDetailVo
     */
    @Override
    public OrderEnterpriseRepaymentDetailVo getEnterpriseRepayment(Long orderCode) {
        // 查询订单信息
        OrderEnterpriseDto enterpriseDto = orderEnterpriseService.getEnterprise(orderCode);
        if (enterpriseDto == null) {
            logger.error("查询企业订单还款信息失败，订单({})不存在", orderCode);
            throw new RuntimeException("查询企业订单还款信息失败");
        }

        // 查询排期信息
        List<EnterpriseScheduleBizDto> scheduleBizDtos = enterpriseScheduleBizService.getSchedule(orderCode);
        if (scheduleBizDtos == null || scheduleBizDtos.isEmpty()) {
            return null;
        }
        OrderEnterpriseRepaymentDetailVo result = new OrderEnterpriseRepaymentDetailVo();
        result.setOrderCode(orderCode);
        result.setHasPayAmount(enterpriseDto.getDeposit());
        result.setArrivalAmount(BigDecimal.ZERO);
        result.setRepaymentDetail(new ArrayList<>(scheduleBizDtos.size()));
        List<Integer> scheduleIds = new ArrayList<>();
        for (EnterpriseScheduleBizDto scheduleBizDto : scheduleBizDtos) {
            if (null == scheduleBizDto) {
                continue;
            }
            Integer state = scheduleBizDto.getState();
            if (state != null && state == EnterpriseScheduleStateEnum.ALREADY.getValue()) {
                scheduleIds.add(scheduleBizDto.getScheduleId());
            }
            result.getRepaymentDetail().add(Convert.toOrderRepaymentDetailVo(scheduleBizDto));
        }
        result.getRepaymentDetail().get(0).setDeposit(enterpriseDto.getDeposit());
        if (!scheduleIds.isEmpty()) {
            // 查询支付信息
            Map<Integer, PaymentEnterpriseDto> paymentMap = paymentEnterpriseService.getEnterprise(scheduleIds);
            if (paymentMap == null || paymentMap.isEmpty()) {
                return result;
            }
            for (OrderRepaymentDetailVo orderRepaymentDetailVo : result.getRepaymentDetail()) {
                if (orderRepaymentDetailVo.getStatus() != EnterpriseScheduleStateEnum.ALREADY.getValue()) {
                    break;
                }
                PaymentEnterpriseDto paymentEnterpriseDto = paymentMap.get(orderRepaymentDetailVo.getId());
                result.setHasPayAmount(result.getHasPayAmount().add(orderRepaymentDetailVo.getPayable()));
                result.setArrivalAmount(result.getArrivalAmount().add(paymentEnterpriseDto.getArrivalAmount()));

                orderRepaymentDetailVo.setArrivalAmount(paymentEnterpriseDto.getArrivalAmount());
                orderRepaymentDetailVo.setArrivalAmountStr(paymentEnterpriseDto.getArrivalAmount()
                        .stripTrailingZeros().toPlainString() + "元");
                orderRepaymentDetailVo.setSerialNumber(paymentEnterpriseDto.getSerialNumber());
                orderRepaymentDetailVo.setRemark(paymentEnterpriseDto.getRemark());
            }
        }

        return result;
    }

    /**
     * 新增企业订单
     *
     * @param createVo 新增信息
     * @return boolean
     */
    @Override
    public boolean create(OrderEnterpriseCreateVo createVo) throws Exception {
        if (createVo.getContractUrls().get(0) == null
                || StringUtils.isBlank(createVo.getContractUrls().get(0).getContractName())
                || StringUtils.isBlank(createVo.getContractUrls().get(0).getContractUrl())) {
            throw new RuntimeException("合同信息不能为空");
        }

        // 新增合同
        ContractEnterpriseCreateDto contractCreateDto = Convert.toContractEnterpriseCreateDto(createVo);
        Integer contractId = contractEnterpriseService.createContract(contractCreateDto);

        // 新增订单
        Long orderCode = null;
        if (createVo.getPrentOrderCode() == null) {
            // 新订单
            List<Integer> carIds = new ArrayList<>();
            createVo.getCars().forEach(carVo -> {
                carIds.add(carVo.getCarId());
            });
            Map<Integer, CarDto> carMap = carService.getCarByIds(carIds);
            if (carMap.size() != createVo.getCars().size()) {
                logger.error("新增订单车辆信息异常，车辆不存在");
                throw new RuntimeException("新增订单车辆信息异常");
            }
            // 检验车辆状态
            for (CarDto carDto : carMap.values()) {
                if (carDto.getStockType() != CarsStockTypeEnum.STOCK.getValue()) {
                    logger.error("新增订单车辆信息异常，车辆({})不属于中转库({}:{})", carDto.getId(),
                            carDto.getStockType(), carDto.getStockId());
                    throw new RuntimeException("新增订单车辆信息异常");
                } else if (carDto.getStatus() != CarsOperateStatusEnum.FOR_RENT.getValue()) {
                    logger.error("新增订单车辆信息异常，车辆({})不属于可租状态({})", carDto.getId(), carDto.getStatus());
                    throw new RuntimeException("新增订单车辆信息异常");
                }
            }
            // 新增企业订单
            orderCode = orderEnterpriseBizService.create(Convert.toOrderEnterpriseCreateBizDto(createVo, carMap));
        } else {
            // 续订单
            List<EnterpriseCarDto> enterpriseCars = enterpriseCarService.getEnterpriseCar(
                    createVo.getPrentOrderCode(), EnterpriseCarStateEnum.LEASE);
            if (enterpriseCars.size() != createVo.getCars().size()) {
                logger.error("续订订单车辆信息异常，车辆数量和父订单不符");
                throw new RuntimeException("续订订单车辆信息异常");
            }
            Map<Integer, EnterpriseCarDto> enterpriseCarMap = enterpriseCars.stream()
                    .collect(Collectors.toMap(EnterpriseCarDto::getCarId, enterpriseCar -> enterpriseCar));
            // 新增企业订单
            orderCode = orderEnterpriseBizService.create(Convert.toRenewOrderEnterpriseCreateBizDto(createVo, enterpriseCarMap));
        }

        if (orderCode == null || orderCode <= 0L) {
            return false;
        }

        // 订单新增成功后，合同添加订单号
        contractEnterpriseService.modifyOrderCode(contractId, orderCode);

        return true;
    }

    /**
     * 订单支付/还款
     *
     * @param createVo 付款信息
     * @return boolean
     */
    @Override
    public boolean createPay(EnterprisePayCreateVo createVo) {
        // 支付修改订单信息
        if (!orderEnterpriseBizService.modifyPay(Convert.toEnterprisePayModifyBizDto(createVo))) {
            return false;
        }

        EnterpriseScheduleDto scheduleDto = null;
        Integer scheduleId = createVo.getScheduleId();
        // 判断是否首付
        if (scheduleId == null || scheduleId == 0) {
            // 首付查询首付排期id
            scheduleDto = enterpriseScheduleService.getSchedule(createVo.getOrderCode(), 1);
        } else {
            scheduleDto = enterpriseScheduleService.getScheduleById(scheduleId);
        }
        if (scheduleDto == null) {
            logger.error("订单({})排期({})不存在", createVo.getOrderCode(), scheduleId);
        } else if (!scheduleDto.getOrderCode().equals(createVo.getOrderCode())) {
            logger.error("订单({})和排期({})订单({})不一致", createVo.getOrderCode(), scheduleId, scheduleDto.getOrderCode());
            return false;
        }

        // 新增支付信息
        PaymentEnterpriseCreateDto payCreateDto = Convert.toPaymentEnterpriseCreateDto(createVo);
        payCreateDto.setScheduleId(scheduleDto.getScheduleId());
        payCreateDto.setRepaymentPeriods(scheduleDto.getPeriods());
        payCreateDto.setEnterpriseId(scheduleDto.getEnterpriseId());
        paymentEnterpriseService.create(payCreateDto);

        return true;
    }

    /**
     * 验证企业订单还款
     *
     * @param orderCode  订单号
     * @param scheduleId 排期id
     * @return EnterpriseScheduleVerifyVo
     */
    @Override
    public EnterpriseScheduleVerifyVo getVerifyRepay(Long orderCode, Integer scheduleId) {
        EnterpriseScheduleVerifyVo result;
        // 根据订单号查询当前应还排期信息
        EnterpriseScheduleDto currentScheduleDto = enterpriseScheduleService.getCurrent(orderCode);
        if (currentScheduleDto == null) {
            logger.error("订单({})不存在排期或未还排期", orderCode);
            throw new RuntimeException("订单不存在或已还清");
        }
        result = Convert.toEnterpriseScheduleVerifyVo(currentScheduleDto);
        if (!currentScheduleDto.getScheduleId().equals(scheduleId)) {
            result.setVerify(false);
            result.setMsg("当前订单存在更早的未还款计划，是否对其还款？");
        } else {
            result.setVerify(true);
        }

        return result;
    }

    /**
     * 查询订单和车辆信息
     *
     * @param orderCode 订单号
     * @return EnterpriseVo
     */
    @Override
    public EnterpriseAndCarVo getEnterprise(Long orderCode) {
        // 根据订单号查询订单信息
        OrderEnterpriseDto enterprise = orderEnterpriseService.getEnterprise(orderCode);
        if (enterprise == null) {
            throw new BizException("订单不存在");
        }
        // 查询所有租赁中的车辆
        List<EnterpriseCarDto> enterpriseCars = enterpriseCarService.getEnterpriseCar(orderCode, EnterpriseCarStateEnum.LEASE);

        if (enterpriseCars == null || enterpriseCars.isEmpty()) {
            return Convert.toEnterpriseAndCarVo(enterprise, null, null, null, null);
        }

        Map<Integer, List<EnterpriseCarDto>> enterpriseCarMap = new HashMap<>();
        // 车辆ids
        List<Integer> carIds = new ArrayList<>(enterpriseCars.size());
        // 车型ids
        Set<Integer> modelIdSet = new HashSet<>();
        // 颜色ids
        Set<Integer> colorIdSet = new HashSet<>();
        for (EnterpriseCarDto dto : enterpriseCars) {
            colorIdSet.add(dto.getColorId());
            carIds.add(dto.getCarId());
            modelIdSet.add(dto.getModelId());
            if (enterpriseCarMap.get(dto.getModelId()) == null) {
                List<EnterpriseCarDto> list = new ArrayList<>();
                list.add(dto);
                enterpriseCarMap.put(dto.getModelId(), list);
            } else {
                enterpriseCarMap.get(dto.getModelId()).add(dto);
            }
        }
        // 查询车辆
        Map<Integer, CarDto> carMap = carService.getCarByIds(carIds);
        // 查询车型
        ArrayList<Integer> ids = new ArrayList<>(modelIdSet.size());
        ids.addAll(modelIdSet);
        Map<Integer, VehicleNameBizDto> vehicleMap = vehicleBizService.getCarByModelNameList(ids);
        // 查询颜色
        ids = new ArrayList<>(colorIdSet.size());
        ids.addAll(colorIdSet);
        Map<Integer, VehicleColorDto> colorMap = vehicleColorService.getVehicleColors(ids);


        return Convert.toEnterpriseAndCarVo(enterprise, enterpriseCarMap, carMap, vehicleMap, colorMap);
    }

    /**
     * 订单列表
     */
    @Override
    public Paged<OrderEnterpriseListVo> orderEnterpriseList(Map<String, Object> params, Integer pageNum, Integer pageSize) {

        logger.info("查询企业订单列表-入参："+params);
        Paged<OrderEnterpriseListVo> result = new Paged<>(new ArrayList<>(), 0, pageSize);

        Paged<OrderEnterpriseBizDto> orderEnterpriseListDtoPage = null;
        try {
            orderEnterpriseListDtoPage = orderEnterpriseBizService
                    .getOrderList(params, pageNum, pageSize);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 判断是否查询为空
        if (orderEnterpriseListDtoPage == null) {
            return result;
        } else if (orderEnterpriseListDtoPage.isEmpty()) {
            result.setTab(orderEnterpriseListDtoPage.getTab());
            return result.setTotal(orderEnterpriseListDtoPage.getTotal());
        }
        result.setTab(orderEnterpriseListDtoPage.getTab());
        result.setTotal(orderEnterpriseListDtoPage.getTotal());
        List<Long> orderCodes = new ArrayList<>();
        for (OrderEnterpriseBizDto orderEnterpriseBizDto : orderEnterpriseListDtoPage
                .getList()) {
            if (orderEnterpriseBizDto != null) {
                orderCodes.add(orderEnterpriseBizDto.getOrderCode());
            }
        }

        Map<Long, ContractEnterpriseDto> conMap = null;
        // 统计每种状态下的数据
        EnterpriseStateEnum enterpriseStateEnum = null;
        if (params.get("state") != null) {
            enterpriseStateEnum = ObjectCastUtil.castEmun(params.get("state"), EnterpriseStateEnum.class);
        }

        if(params.get("state")==null
                || EnterpriseStateEnum.UNPAID.getValue()==(Integer.parseInt(params.get("state").toString()) )
                || EnterpriseStateEnum.UNDELIVERY.getValue()==(Integer.parseInt(params.get("state").toString()) )
                || EnterpriseStateEnum.UNHIRE.getValue()==(Integer.parseInt(params.get("state").toString()))) {

            conMap = contractEnterpriseService.getContractMapByOrderCodes(orderCodes);
            logger.info("起租确认-合同集合 >> "+(conMap==null?0:conMap.size()));
        }

        // 用户id集合
        List<Integer> userIds = new ArrayList<>();
        for (OrderEnterpriseBizDto orderEnterpriseBizDto : orderEnterpriseListDtoPage
                .getList()) {
            OrderEnterpriseListVo vo = Convert.toEnterpriseListBizVo(orderEnterpriseBizDto);
            if (conMap != null && conMap.get(vo.getOrderCode()) != null) {
                logger.info("起租确认-合同签单时间 >> "+conMap.get(vo.getOrderCode()).getContractDate());
                vo.setContractDate(conMap.get(vo.getOrderCode()).getContractDate());
            }
            result.getList().add(vo);
        }

        return result;
    }

    @Override
    public Paged<OrderEnterpriseCarBizVo> orderEnterpriseCarList(Map<String, Object> params, Integer pageNum, Integer pageSize) {
        Paged<OrderEnterpriseCarBizVo> result = new Paged<>(new ArrayList<>(), 0, pageSize);

        Paged<OrderEnterpriseCarBizDto> orderEnterpriseListDtoPage = null;
        try {
            orderEnterpriseListDtoPage = orderEnterpriseBizService
                    .getOrderEnterpriseCarList(params, pageNum, pageSize);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 判断是否查询为空
        if (orderEnterpriseListDtoPage == null) {
            return result;
        } else if (orderEnterpriseListDtoPage.isEmpty()) {
            result.setTab(orderEnterpriseListDtoPage.getTab());
            return result.setTotal(orderEnterpriseListDtoPage.getTotal());
        }
        result.setTab(orderEnterpriseListDtoPage.getTab());
        result.setTotal(orderEnterpriseListDtoPage.getTotal());

        // 用户id集合
        List<Integer> vehicleIds = new ArrayList<>();

        List<Long> orderCodes = new ArrayList<>();


        for (OrderEnterpriseCarBizDto bizDto : orderEnterpriseListDtoPage
                .getList()) {
            orderCodes.add(bizDto.getOrderCode());
            vehicleIds.add(bizDto.getModelId());
            result.getList().add(Convert.toEnterpriseCarBizVo(bizDto));
        }

        //查询合同-订单签订日
        Map<Long, ContractEnterpriseDto> conMap = contractEnterpriseService.getContractMapByOrderCodes(orderCodes);

        //拼接车型
        // 查询车型名称
        Map<Integer, String> vehicleModelMap = vehicleBizService.getVehicleFullName(vehicleIds);

        for (OrderEnterpriseCarBizVo vo : result.getList()) {
            // 车型名称
            vo.setModelName(vehicleModelMap == null ? null : vehicleModelMap.get(vo.getModelId()));
            ContractEnterpriseDto cdto = conMap.get(vo.getOrderCode());
            vo.setContractSignDate(cdto == null ? null : cdto.getContractDate());
        }

        return result;
    }

    /**
     * 起租确认
     *
     * @param createVo
     * @return
     */
    @Override
    public Boolean leaseConfirm(EnterpriseLeaseConfirmCreateVo createVo) {

        logger.info("【起租确认】入参："+createVo);
        //判断如果起租日小于合同签订日或起租日大于当前时间，则不合法
        List<Long> orderCodes = new ArrayList<>();
        orderCodes.add(createVo.getOrderCode());
        Map<Long, ContractEnterpriseDto> map = contractEnterpriseService.getContractMapByOrderCodes(orderCodes);
        ContractEnterpriseDto dto = map.get(createVo.getOrderCode());
        LocalDate inception = DateUtil.parseDate(createVo.getLeaseInception());
        if(dto==null  || dto.getContractDate()==null){
            logger.error("【起租确认】订单合同时间为null"+createVo);
            return false;
        }
        if(inception.isAfter(LocalDate.now()) || inception.isBefore(dto.getContractDate())){
            logger.info("【起租确认】起租时间未在合法范围："+createVo);
            return false;
        }

        // 新增企业订单
        Boolean bool = orderEnterpriseBizService.leaseConfirm(Convert.toOrderEnterpriseLeaseConfirmBizDto(createVo));
        if (bool == null ) {
            logger.info("【起租确认】调用服务失败："+createVo);
            return false;
        }
        logger.info("【起租确认】成功："+createVo);
        return bool;
    }

    @Override
    public List<OrderTradeFlowVo> getEnterpriseStateFlow(Long orderCode) throws Exception {
        return orderCode == null ? null
                : Convert.toOrderTradeFlowVo(orderEnterpriseBizService.getOrderFlow(orderCode));
    }

    @Override
    public List<OrderEnterpriseListVo> getListByCarId(Integer carId) {
        logger.info("根据车辆ID查询企业订单：" + carId);
        List<OrderEnterpriseBizDto> list = orderEnterpriseBizService.getListByCarId(carId);
        if (list == null || list.isEmpty()) {
            return null;
        }
        List<OrderEnterpriseListVo> res = new ArrayList<>();
        for (OrderEnterpriseBizDto dto : list) {
            if (dto == null || dto.getState() == null) {
                continue;
            }
            OrderEnterpriseListVo vo = new OrderEnterpriseListVo();
            BeanUtils.copyProperties(dto, vo);
            vo.setStateStr(EnterpriseStateEnum.getName(dto.getState()));
            res.add(vo);
        }
        return res;
    }

    /**
     * 根据订单号获取车型、车辆信息
     * @param orderCode
     * @return
     */
    @Override
    public List<OrderEnterpriseModelCarVo> getOrderEnterpriseModelCar(Long orderCode) {
        logger.info("订单号获取车型、车辆信息:"+orderCode);
        List<EnterpriseCarDto> list = enterpriseCarService.getEnterpriseCar(orderCode);
        if(list!=null && list.size()>0){
            List<OrderEnterpriseModelCarVo> result = new ArrayList<>();
            List<Integer> modelIds = new ArrayList<>();
            for (EnterpriseCarDto carDto : list) {
                if(carDto!=null){

                    if(carDto.getModelId()!=null){
                        modelIds.add(carDto.getModelId());
                    }

                    OrderEnterpriseModelCarVo vo = new OrderEnterpriseModelCarVo();
                    BeanUtils.copyProperties(carDto,vo);
                    result.add(vo);
                }
            }

            Map<Integer, String> vehicleModelMap = vehicleBizService.getVehicleFullName(modelIds);

                if(result.size()>0 && vehicleModelMap!=null && vehicleModelMap.size()>0){
                    for (OrderEnterpriseModelCarVo vo : result) {
                            vo.setModelName(vehicleModelMap.get(vo.getModelId()));
                    }
                }
                return result;
        }
        return null;
    }
}
